Regular Expressions


Regular expressions (regex or regexp) are sequences of characters that form search patterns. They are used for pattern matching within strings, allowing for complex search and replace operations.

Basic Syntax

A regular expression can be created using the RegExp constructor or by using forward slashes to enclose the pattern.

let regex1 = new RegExp("pattern");
let regex2 = /pattern/;

Common Metacharacters

Examples

Here are some examples of using regular expressions in JavaScript:

let regex = /\d+/;
console.log(regex.test("123")); // true
console.log(regex.test("abc")); // false

let str = "Hello, World!";
let result = str.replace(/World/, "JavaScript");
console.log(result); // Hello, JavaScript!

Flags

Regular expressions can have optional flags that affect the search:

For more detailed information, you can check out resources like MDN Web Docs and W3Schools.